import commonAttachmentUploadTpl from './commonAttachmentUpload.html';

function commonAttachmentUploadComponent() {
  'ngInject';

  function linkFn(scope, elements, attrs, ctrl) {
    setTimeout(ctrl.initUploader, 1700);
    ctrl.isUploading = false;
  }

  let directive = {
    restrict: 'E',
    replace: true,
    templateUrl: commonAttachmentUploadTpl,
    controller: commonAttachmentUploadController,
    controllerAs: 'commonAttachmentUploadCtrl',
    bindToController: {
      fileType: '@', // 上传文件类型 image: 图片, file: 文件
      fileList: '=',  // 用于绑定上传成返回的token和展示列表
      componentId: '@', // 传递组件id
      pickBtnId: '@', // 传递上传图片按钮id
      uploadUrl: '@', // 上传url
      isUploading: '=', // 是否上传完成
    },
    link: linkFn,
  };

  function commonAttachmentUploadController($scope, fileUploaderService, $timeout) {
    'ngInject';
    let _this = this;
    this.webuploader = {}; // WebUploader.create()返回的实例对象
    const FILE_NUM_LIMIT = 50;

    // 获得文件路径
    this.getFileSrc = (file) => {
      if (file.filePath) {
        let src = `${SERVER_IP}/${file.filePath}`;
        return src;
      } else if (file.dataUrl){
        return file.dataUrl;
      }
      return '';      
    }

    // 删除文件
    this.delete = (item) => {
      let index = this.fileList.indexOf(item);
      if (index >= 0) {
        this.fileList.splice(index, 1);
      }
      let fileId = item.webuploaderFileId;
      if (fileId) {
        this.webuploader.removeFile(fileId);
      }
    }

    function beforeFileQueuedCB() {
      // 如果传入的property是空则赋值为数组
      if (!_this.fileList) _this.fileList = [];

      if (_this.fileList.length >= FILE_NUM_LIMIT) {
        layer.alert(`最多可上传${FILE_NUM_LIMIT}个文件`);
        return false;
      }
    }

    function fileQueuedCB() {
      $scope.$apply(() => {
        _this.isUploading = true;
      });
    };

    // 文件上传成功回调函数
    function uploadSuccessCB(file, resp) {   
      // this指向fileUploader
      let webuploader = this;
      let respToken = resp.message;
      $scope.$apply(() => {
        _this.isUploading = false;
      });

      _this.webuploader.makeThumb(file, (error, src) => {
        $scope.$apply(() => {
          _this.fileList.push({
            id: respToken,
            fileName: file.name,
            dataUrl: src,
            webuploaderFileId: file.id,  // webuploader file 的id
          });
        });
      }, 100, 100);

      // toast提示
      layer.msg(`${file.name}上传成功`);
    }

    // 文件上传失败回调函数
    function uploadErrorCB(file, reason) {
      $scope.$apply(() => {
        _this.isUploading = false;
        _this.delete(file);
      });
      layer.alert('文件上传失败');
    }

    // 文件上传过程中创建进度条实时显示
    function uploadProgressCB(file, percentage) {
      $('.progress').show();
      $('.rate').css('width',  percentage * 100 + '%');
      $('.text').text(parseInt(percentage * 100) + '%');
      if (percentage == 1) {
        $('.rate').css('width', '0%');
        $('.progress').hide();
      }
    }

    // 上传设备基本信息
    this.initUploader = () => {
      let acceptType = null;
      if (this.fileType == 'image') {
        acceptType = {
          title: 'Images',
          extensions: 'gif,jpg,jpeg,bmp,png',
          mimeTypes: 'image/*'
        }
      }
      
      // 初始化uploader
      let webuploader = fileUploaderService.initUploader({
        auto: true,
        pick: {
          id: `#${_this.pickBtnId}`,
          multiple: false,
        },
        duplicate: false,
        server: this.uploadUrl,
        accept: acceptType,
      }, fileQueuedCB, uploadSuccessCB, uploadErrorCB);

      this.webuploader = webuploader;

      // 监听错误类型
      webuploader.on('error', function(type) {
        if (type == 'Q_EXCEED_NUM_LIMIT') {
          layer.alert(`最多可上传${FILE_NUM_LIMIT}个文件`);
        } else if (type == 'Q_TYPE_DENIED') {
          layer.alert('文件类型错误');
        } else if (type == 'F_DUPLICATE'){
          layer.alert('文件已上传');
        }
      });

      // 监听是否超出文件最大上传数量
      webuploader.on('beforeFileQueued', beforeFileQueuedCB);

      // 进度条
      webuploader.on('uploadProgress', uploadProgressCB);
    }

    // setTimeout(this.initUploader, 1200);
      
  }

  return directive;
}

export default commonAttachmentUploadComponent;
